import { defineStore } from 'pinia';
import { messageApi, accountApi } from '@/services/api';

export const useMessageStore = defineStore('message', {
  state: () => ({
    accounts: [],
    currentAccount: null,
    logs: [],
    totalLogs: 0,
    loading: false
  }),
  
  actions: {
    async loadAccounts() {
      try {
        const response = await accountApi.getAllAccounts();
        this.accounts = response.data;
        if (this.accounts.length > 0 && !this.currentAccount) {
          this.currentAccount = this.accounts[0];
        }
      } catch (error) {
        console.error('加载账号失败', error);
      }
    },
    
    async setCurrentAccount(accountId) {
      try {
        await accountApi.setCurrentAccount(accountId);
        this.currentAccount = this.accounts.find(a => a.accountId === accountId);
      } catch (error) {
        console.error('设置账号失败', error);
      }
    },
    
    async sendMessage(content, userIds, jumpUrl) {
      this.loading = true;
      try {
        const response = await messageApi.sendMessage({
          content,
          userIds,
          jumpUrl
        });
        return response.data;
      } catch (error) {
        console.error('发送消息失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async queryLogs(page = 1, size = 10, sender = null) {
      this.loading = true;
      try {
        const params = { page, size };
        if (sender) params.sender = sender;
        
        const response = await messageApi.queryLogs(params);
        this.logs = response.data.items;
        this.totalLogs = response.data.total;
      } catch (error) {
        console.error('查询日志失败', error);
      } finally {
        this.loading = false;
      }
    }
  }
});